package utils

import (
	"errors"
	"github.com/MzoroHaHa/dev-tools/backend/app/logger"
	"net"
	"strconv"
	"time"
)

var utilsLogger = logger.NewLogger("utils")

func FindPort(basePort uint, largest uint) (uint, error) {

	if basePort > largest {
		return basePort, errors.New("base port is larger than largest")
	}
	for port := basePort; port <= largest; port++ {
		if !PortInUse(port) {
			return port, nil
		}
	}
	return 0, errors.New("no suitable port")

}

func PortInUse(_port uint) bool {
	host := "localhost"
	port := strconv.Itoa(int(_port))
	timeout := time.Millisecond * 100
	conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
	if err != nil {
		utilsLogger.Error("port: " + port + " is in use. ")
		return false
	}
	if conn != nil {
		defer conn.Close()
		return true
	}
	return false
}
